<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示框 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <el-steps :space="200" :active="activeIndex-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="动态参数"></el-step>
        <el-step title="静态参数"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="已完成"></el-step>
      </el-steps>
      <!-- 侧边栏列表 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeLeave" @tab-click="handleTab">
          <el-tab-pane label="基本信息" name='0'>
            <el-form-item label="商品名称" prop="godds_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" type="number" prop="godds_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" type="number" prop="godds_weigth">
              <el-input v-model="addForm.goods_weigth"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" type="number" prop="godds_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader expandTrigger='hover' v-model="addForm.goods_cat" :options="cateList" :props="cateProps"
                @change="handleChange" clearable></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数(动态)" name='1'>
            <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <br>
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item1" v-for="(item1,index1) in item.attr_vals1" :key="index1">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性(静态)" name='2'>
            <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3'>
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture"
              :headers="headerObj" :on-success="handleSuccess" :file-list="filesList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4'>
            <quill-editor v-model="addForm. goods_introduce"></quill-editor>
            <el-button type="primary" @click="addShop" style="margin:15px 0">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片弹出框 -->
    <el-dialog :visible.sync="previewVisible" width="50%">
      <img :src=" previewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      // 控制图片预览
      previewVisible: false,
      previewPath: '',
      // 请求头获取main中的
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      uploadURL: 'http://42.192.71.221:8889/api/private/v1/upload',
      cateList: [],
      filesList: [],
      manyTableData: [],
      onlyTableData: [],
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weigth: 0,
        goods_cat: [1, 3, 6],
        goods_introduce: '',
        // 图片
        pics: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_weigth: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getcateList()
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    addShop () {
      this.$refs.addFormRef.validate(async flag => {
        if (!flag) return this.$message.error('校验失败')
        const form = cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)
        console.log(form === this.addForm)
        form.attrs = []
        this.manyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('失败')
        this.$message.success('成功')
        this.$router.go(-1)
      })
    },
    handleSuccess (response) {
      this.addForm.pics.push({ pic: response.data.tmp_path })
    },
    // 预览
    handlePreview (file) {
      // 当用户点击图片进行预览时执行，处理图片预览
      // 形参file就是用户预览的那个文件
      this.previewPath = 'http://42.192.71.221:8889/' + file.response.tem_path
      // 显示预览图片对话框
      this.previewVisible = true
    },
    // 移除操作
    handleRemove (file) {
      this.filePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(x => x.pic === this.filePath)
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    async handleTab () {
      if (this.activeIndex === '1') {
        // 发送请求获取动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'many' } }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数列表失败')
        }
        // 将attr_vals字符串转换为数组
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        // 发送请求获取静态属性
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'only' } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性列表失败')
        }
        console.log(res.data)
        this.onlyTableData = res.data
      }
    },
    beforeLeave (to, from) {
      if (from === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('选这三级')
        return false
      }
    },
    async getcateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    handleChange () {
      // 如果用户选择的不是三级分类,该次选择无效，因为必须选择三级分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    }

  }
}
</script>

<style lang="less" scoped>
.previewImg {
  width: 100%;
}
/deep/ .ql-editor {
  min-height: 300px;
}
</style>
